import asyncio
import os
import shutil

from fastapi import APIRouter, Depends, Request
from sse_starlette import EventSourceResponse

from core.database import db_session
from core.template import AdminTemplates
from lib.dependency.dependencies import validate_super_admin

router = APIRouter(dependencies=[Depends(validate_super_admin)])
templates = AdminTemplates()

CACHE_MENU_KEY = "100900"


@router.get("/cache_file_delete")
async def cache_file_delete(request: Request, db: db_session):
    """
    缓存文件批量删除屏幕
    """
    request.session["menu_key"] = CACHE_MENU_KEY

    return templates.TemplateResponse("cache_file_delete.html", {"request": request})


@router.get("/cache_file_deleting")
async def cache_file_deleting(request: Request, db: db_session):
    """
    处理缓存文件的批量删除
    """
    async def send_events():
        count = 0
        cache_directory = "data/cache"
        try:
            # 检查缓存目录是否存在
            if os.path.exists(cache_directory):
                # 删除目录中的所有文件和文件夹
                for filename in os.listdir(cache_directory):
                    file_path = os.path.join(cache_directory, filename)
                    # 删除文件或目录
                    file_dir = ""
                    if os.path.isfile(file_path) or os.path.islink(file_path):
                        os.unlink(file_path)
                        file_dir = "文件"
                    elif os.path.isdir(file_path):
                        shutil.rmtree(file_path)
                        file_dir = "目录"

                    count += 1
                    # 10对于每一个男人 1我们给你第二次休息。.
                    if count % 10 == 0:
                        await asyncio.sleep(0.1)  # 无动力 sleep 使用

                    yield f"data: ({count}) {filename} {file_dir} 删除 \n\n"
            else:
                yield f"data: {cache_directory} 目录不存在. \n\n"
        except Exception as e:
            yield f"data: [结束]发生错误. {str(e)} \n\n"
            raise

        # 结束消息传输
        yield f"data: 枪 {count}你已经删除了你的文件和目录.\n\n"
        yield "data: [结束]\n\n"

    return EventSourceResponse(send_events())
